﻿using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using SSC.Models;
using SSC.Services;
using SSC.BaseClass;

namespace SSC.ViewModels
{
    public class AlarmLogViewModel : NotifyBase
    {
        private readonly AlarmLogService _service;

        public AlarmLogViewModel()
        {
            _service = new AlarmLogService();
            Logs = new ObservableCollection<AlarmLog>();

            StartDate = DateTime.Now.AddDays(-1);
            EndDate = DateTime.Now;

            SearchCommand = new RelayCommand(_ => Search());
            ExportCommand = new RelayCommand(_ => Export());
        }

        public ObservableCollection<AlarmLog> Logs { get; }

        private DateTime _startDate;
        public DateTime StartDate
        {
            get => _startDate;
            set => SetProperty(ref _startDate, value);
        }

        private DateTime _endDate;
        public DateTime EndDate
        {
            get => _endDate;
            set => SetProperty(ref _endDate, value);
        }

        public ICommand SearchCommand { get; }
        public ICommand ExportCommand { get; }

        private void Search()
        {
            Logs.Clear();
            var result = _service.QueryLogs(StartDate, EndDate);
            foreach (var log in result)
                Logs.Add(log);
        }

        private void Export()
        {
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                Filter = "CSV 文件 (*.csv)|*.csv",
                FileName = "报警记录.csv"
            };

            if (dlg.ShowDialog() == true)
            {
                using var writer = new System.IO.StreamWriter(dlg.FileName);
                writer.WriteLine("ID,地址,内容,开始时间,结束时间,备用");
                foreach (var log in Logs)
                {
                    writer.WriteLine($"{log.Id},{log.AlarmAddress},{log.AlarmMessage},{log.StartTime},{log.EndTime},{log.Spare}");
                }

                System.Windows.MessageBox.Show("导出成功");
            }
        }
    }
}
